package com.cdshangpai.utils.storage;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.cdshangpai.PhotoappApplication;
import com.cdshangpai.photoapp.LogConfig;
import com.cdshangpai.utils.api.Api;
import com.cdshangpai.utils.api.NetConfig;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class DownloadUtil {
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
        okHttpClient.setConnectTimeout(NetConfig.connectTimeout, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(NetConfig.readTimeout,TimeUnit.SECONDS);
    }

    public void download( String url,  String saveDir,boolean encryption, OnDownloadListener listener)
    {
        String realUrl="";
        String test=url.substring(0,4).toLowerCase();
        if(!url.substring(0,4).toLowerCase().equals("http"))
        {
            realUrl=Api.imagehost+url;
        }
        else
        {
            realUrl=url;
        }
        doDownload(realUrl,saveDir,encryption,listener);
    }

    /**
     * @param url 下载连接
     * @param saveDir 储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public void doDownload(final String url, final String saveDir,boolean encryption, final OnDownloadListener listener) {
//        Log.i(LogConfig.logTag,"开始下载"+url);
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Request request, IOException e) {
                listener.onDownloadFailed();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                Boolean success=false;
                String fileName="";
                FileOutput fileOutput=null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fileName= UUID.randomUUID().toString().replace("-","")+"_"+getNameFromUrl(url);
                    fileOutput=new FileOutput(PhotoappApplication.context,saveDir,fileName);

//                    Log.i(LogConfig.logTag,"本次准备下载的文件命名"+fileName);

                    //本地文件创建失败，返回错误
                    if(!fileOutput.isSeccess())
                    {
                        listener.onDownloadFailed();
                        return;
                    }

                    if(encryption)
                    {
                        fileOutput.write(ImageManager.encryptionbuf);
                    }

                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fileOutput.write(buf,0,len);
                        fileOutput.flush();

                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
//                        Log.i(LogConfig.logTag,"下载进度"+progress);
                        // 下载中
                        listener.onDownloading(progress);
                    }
                    // 下载完成
//                    Log.i(LogConfig.logTag,"完成下载的文件:"+fileName);
                    success=true;
                } catch (Exception e) {
//                    Log.i(LogConfig.logTag,"下载过程错误，"+e.getMessage());
                    success=false;
                } finally {
                    try {
                        if (is != null)
                            is.close();

                        fileOutput.flush();
                        fileOutput.close();

//                        Log.i(LogConfig.logTag,"完成下载后关闭输入流");
                    } catch (Exception e) {
                        Log.i(LogConfig.logTag,"完成下载后清理出现问题");
                        e.printStackTrace();
                    }
                }

                if(success)
                {
                    //下载成功
                    listener.onDownloadSuccess(fileOutput.pickFileName());
                }
                else
                {
                    //下载失败，清理零时下载的文件
                    //删除已经下载的文件
                    if(!TextUtils.isEmpty(fileName)&&fileOutput!=null)
                    {
                        String uri=fileOutput.pickFileName();
                        FileInput fileInput=new FileInput(PhotoappApplication.context);
                        fileInput.delete(saveDir,uri);
//                        Log.i(LogConfig.logTag,"成功删除下载过程中失败的文件:"+fileName);
                    }
                    listener.onDownloadFailed();
                }
            }
        });
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException
     * 判断下载目录是否存在
     */
    private void isExistDir(String saveDir) throws IOException {
        File file=new File(saveDir);
        if(!file.exists())
        {
            file.mkdirs();
        }


        // 下载位置
//        File downloadFile = new File(Environment.getExternalStorageDirectory()+File.separator+"photoapp", saveDir);
//        if (!downloadFile.mkdirs()) {
//            downloadFile.createNewFile();
//        }
//        String savePath = downloadFile.getAbsolutePath();
//        return savePath;
    }

    /**
     * @param url
     * @return
     * 从下载连接中解析出文件名
     */
    @NonNull
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}
